package stdio.costa.imoca.spi;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import stdio.costa.imoca.dao.PostcardBackDao;
import stdio.costa.imoca.model.Activity;
import stdio.costa.imoca.model.PostcardBack;
import stdio.costa.imoca.utils.SearchHelper;

@Component
public class PostcardBackSpi {

	@Autowired
	private PostcardBackDao postcardBackDao;

	public PostcardBack save(PostcardBack postcardBack) {
		this.postcardBackDao.save(postcardBack);
		return postcardBack;
	}

	public List<PostcardBack> findPostcardBacksByActivity(Activity activity) {
		return this.postcardBackDao.findPostcardBacksByActivity(activity);
	}

	public PostcardBack findByUuid(String uuid) {
		return this.postcardBackDao.findByUuid(uuid);
	}

	public List<PostcardBack> findByTags(String searchWord) {

		String[] tagsArray = StringUtils.split(searchWord,
				SearchHelper.TAGS_SEPARATORS);

		String hql = "from PostcardBack";

		if (tagsArray.length == 1) {
			hql = hql + "where tags" + " like '%" + searchWord.toLowerCase() + "%'";
		} 
		
		if (tagsArray.length > 1) {
			hql = hql + "where tags" + " like '%" + tagsArray[0].toLowerCase() + "%'";
			
			for (int i = 0; i < tagsArray.length; i++) {
				hql = hql + "and" + " tags " + " like '%" + tagsArray[i] + "%'";
			}
		}
		
		System.out.println(hql);

		return this.postcardBackDao.findByTags(hql);
	}
}
